﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Props.Backend
{
    public class VendorService
    {
        public VendorProfile GetProfileByName(string name)
        {
            var profile = RepositoryFactory.VendorProfiles.GetByName(name);

            if (profile == null)
            {
                profile = GetDefaultProfile(name);
            }

            return profile;
        }

        public VendorAccount GetAccountByName(string name)
        {
            name = name.ToLower();

            return RepositoryFactory.VendorAccounts.GetByName(name);
        }

        public bool AccountExists(string name)
        {
            name = name.ToLower();

            return RepositoryFactory.VendorAccounts.GetByName(name) != null;
        }

        public VendorAccount Register(string name, string email, string password)
        {
            name = name.ToLower();

            VendorAccount account = GetAccountByName(name);

            if (account != null)
                throw new Exception("El nombre de la cuenta ya está en uso.");

            account = new VendorAccount
            {
                Name = name,
                Email = email.ToLower().Trim(),
                Password = password
            };

            RepositoryFactory.VendorAccounts.Save(account);

            return account;
        }

        public void SaveProfile(VendorProfile profile)
        {
            RepositoryFactory.VendorProfiles.Save(profile);
        }

        private VendorProfile GetDefaultProfile(string name)
        {
            return new VendorProfile
            {
                Name = name,
                Title = name,
                Addresses = new string[] { },
                Emails = new string[] { },
                Phones = new string[] { },
                Networks = new string[] { },
                CarrouselItems = new CarrouselItem[] { },
            };
        }

        public bool Verify(string name, string email, string password)
        {
            name = name.ToLower();

            var account = RepositoryFactory.VendorAccounts.GetByName(name);

            if (account == null || !account.Email.Equals(email) || !account.Password.Equals(password))
                return false;

            return true;
        }
    }
}
